package com.hcl.security.config.username;

import com.hcl.security.domain.LoginUser;
import com.hcl.security.domain.User;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class UsernameAuthenticationProvider implements AuthenticationProvider {

	// 重写父类方法，用于进行身份验证
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		// 返回一个Authentication对象，用于存储验证结果
		UsernameForm usernameForm = (UsernameForm) authentication
				.getPrincipal();
		String username = usernameForm.getUsername();
		String password = usernameForm.getPassword();
		if ("admin".equals(username) && "admin".equals(password)) {
			LoginUser loginUser = new LoginUser();
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			loginUser.setUser(user);
			UsernameAuthentication usernameAuthentication = new UsernameAuthentication(
					loginUser, List.of());
			usernameAuthentication.setAuthenticated(true);
			return usernameAuthentication;
		}
		throw new BadCredentialsException("login error");

	}

	@Override
	// 判断传入的authentication是否是UsernameAuthentication的子类或实现类
	public boolean supports(Class<?> authentication) {
		return authentication.isAssignableFrom(UsernameAuthentication.class);
	}
}
